package edu.umn.cs5115.scheduler.search;

import edu.umn.cs5115.scheduler.framework.DocumentController;
import edu.umn.cs5115.scheduler.framework.KeyValueAdapter;
import edu.umn.cs5115.scheduler.framework.KeyValueCoding;
import edu.umn.cs5115.scheduler.framework.KeyValueObserver;
import edu.umn.cs5115.scheduler.framework.KeyValueObserver.SetMutationType;
import java.util.Set;
import org.eclipse.swt.*;
import org.eclipse.swt.widgets.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.graphics.*;


 
public class SearchResultsDisplay
{
    private SearchWindowController windowController;
    
    private List courses;
    private Composite searchResultsPanel;
    private boolean showBackButton = true;
    
    private SearchResults results;
    
    private CourseInfo courseInfo;
    private Button add;
	
    public SearchResultsDisplay(SearchWindowController windowController, SearchResults _results, boolean _showBackButton)
    {
    	//create display, will be passed in real implementation
    	this.windowController = windowController;
    	//initialize search results
        results = _results;
        showBackButton = _showBackButton;
    }
    
    /**
     * Creates and returns the search results interface, adding it to the window 
     * controller's window.
     * @return The created and already-added interface.
     */
    public Composite createSearchResultsInterface()
    {
        if (searchResultsPanel == null)
        {
            buildContent();
        }
        return searchResultsPanel;
    }
    
    /*
     * Driving method for building the shell, 
     * holds large variables, etc.
     */
    private void buildContent() 
    {   	
    	//initialize shell
        searchResultsPanel = new Composite(windowController.getWindow(), SWT.NONE);
        // define the shell as a two column grid
        GridLayout layout = new GridLayout(2, true);
        searchResultsPanel.setLayout(layout);
        
        showSearchParams();
        addLabels();
        //build course list and info section
        if (!results.isSearchCompleted())
        {
            results.addListener(new KeyValueAdapter()
            {
                public void valueChanged(KeyValueCoding object, String key)
                {
                    if (results.isSearchCompleted())
                    {
                        if (!courses.isDisposed())
                        {
                            if (results.getResultsSize() > 0)
                            {
                                courses.setSelection(0);
                                results.setCurrentlySelected(0);
                                courseInfo.setText(results.getCurrentlySelected());
        			if(results.isCourseConsidered(results.getCurrentlySelected()))
        				disableAdd();
        			else
        				enableAdd();
                            } else {
                                courseInfo.setText("No results found.");
                            }
                        }
                        results.removeListener(this, SearchResults.SEARCH_COMPLETED_KEY);
                    }
                }
            },SearchResults.SEARCH_COMPLETED_KEY);
        }
        buildCourseList();
		buildCourseInfo();
		//build all buttons
        buildAddButton();
	    if(showBackButton)
	    	buildBackButton();
		buildDoneButton();
	    
		//pack and open the shell
//		searchResultsPanel.pack();
                if (results.getResultsSize() <= 0)
                {
                    disableAddNoSelection();
                } else {
                    if(results.isCourseConsidered(results.getCurrentlySelected()))
                            disableAdd();
                    else
                            enableAdd();
                }
	}
    


	private void buildCourseList() {
		GridData gridData;
    	//build the courses list
		courses = new List(searchResultsPanel, SWT.SINGLE | SWT.BORDER | SWT.V_SCROLL );
		results.setCourseList(courses);
		if ( courses != null && results.getResultsSize() > 0)
		{
                    courses.setSelection(0);
                    results.setCurrentlySelected(0);
		}
		//only do this if the list contains items
		//courses.setSelection(0);
        courses.addListener(SWT.Selection, new Listener() {
        	public void handleEvent(Event e)
        	{
        		int selection = courses.getSelectionIndex();
        		if(selection > -1)
        		{
        			results.setCurrentlySelected(selection);
        			
        			if(results.isCourseConsidered(results.getCurrentlySelected()))
        				disableAdd();
        			else
        				enableAdd();
        			courseInfo.setText(results.getCurrentlySelected());
        		}
        	}
        });
        
        //List courses, on left side
    	gridData = new GridData(SWT.FILL, SWT.FILL, true, true);
    	
        courses.setToolTipText("Select a class for more information.");
        courses.setLayoutData(gridData);
	}

    private void buildCourseInfo() {
    	GridData gridData;
    	//form element for course info text!
    	gridData = new GridData(SWT.FILL, SWT.FILL, true, true);
        
        courseInfo = new CourseInfo(new StyledText(searchResultsPanel, SWT.WRAP | SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL), gridData);
        courseInfo.setGridData();
        if (results.isSearchCompleted())
        {
            if (results.getResultsSize() > 0)
                courseInfo.setText(results.getCurrentlySelected());
            else
                courseInfo.setText("No results found.");
        } else {
            courseInfo.setText("Searching...please be patient, this may take a few moments.");
        }
    }
	
	private void addLabels()
    {
    	//label for courses
		Label courseLabel = new Label(searchResultsPanel, SWT.BORDER);
		courseLabel.setText("Courses");
		courseLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false));
		
		//label for course info
		Label label = new Label(searchResultsPanel, SWT.BORDER);
		label.setText("Course Information");
		label.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false));

    }
    
    private void buildAddButton()
    {
		GridData gridData;
    	gridData = new GridData(SWT.END, SWT.CENTER, false, false);
		gridData.verticalSpan = 1;
		gridData.horizontalSpan = 2;
		add = new Button(searchResultsPanel, SWT.PUSH );
		//if not already added
		add.setText("Add Selected Course to Courses I am Considering");
		add.addListener(SWT.Selection, new Listener() {
			public void handleEvent(Event event) 
			{
				results.addSelectedToConsideringCourses();
				disableAdd();
			}
			
		});
		add.setLayoutData(gridData);
    }
    
    private void buildBackButton()
    {
    	//initialize button and grid data
    	GridData gridData;
    	Button back = new Button(searchResultsPanel, SWT.PUSH);
	    back.setText("Back To Course Search");
	    gridData = new GridData(SWT.BEGINNING, SWT.CENTER, false, false);
		
		//add listener that returns to main display
		back.addListener(SWT.Selection,new Listener() {
				public void handleEvent(Event event) 
				{
                                    if (!results.isSearchCompleted())
                                        results.cancelSearch();
                    //call function that invokes search
                    windowController.showSearchInterface();
				}
			});
	    back.setLayoutData(gridData);
    }
    
    private void buildDoneButton()
    {
    	//initialize button and grid data
    	GridData gridData = new GridData(SWT.END, SWT.CENTER, false, false);
		if( showBackButton )
			gridData.horizontalSpan = 1;
		else
			gridData.horizontalSpan = 2;
    	Button done = new Button(searchResultsPanel, SWT.PUSH);
	    done.setText("Done!");
	    
		//add listener that quits search result
		done.addListener(SWT.Selection,new Listener() {
				public void handleEvent(Event event) 
				{
                                    if (!results.isSearchCompleted())
                                        results.cancelSearch();
                                    windowController.getWindow().close();
				}
			});
	    done.setLayoutData(gridData);
    }
    
    private void disableAdd()
    {
		add.setText("Course Already Added");
		add.setEnabled(false);
    }
    
    private void disableAddNoSelection()
    {
        add.setText("No Course Selected");
        add.setEnabled(false);
    }
    
    private void enableAdd()
    {
    	add.setText("Add Selected Course to Courses I am Considering");
		add.setEnabled(true);
		add.getParent().layout(new Control[]{add});
    }
    
    private void showSearchParams()
    {
		Group grpBasicInfo = new Group(searchResultsPanel, SWT.BORDER);
		grpBasicInfo.setLayout(new GridLayout(1, false));
		grpBasicInfo.setText("Search Criteria");
		GridData gridData = new GridData();
    	gridData.horizontalSpan = 2;
    	gridData.horizontalAlignment = SWT.CENTER;
		grpBasicInfo.setLayoutData(gridData);
		
    	Label params = new Label(grpBasicInfo, SWT.NONE);
		params.setText(results.getSearchParamList());
    }
    

}